package com.landmesure.communication;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.landmesure.core.TestMessage;

import java.text.ParseException;
import java.util.List;

public abstract class BaseManager {
    public static StringBuffer totalMessage = new StringBuffer();
    public static StringBuffer doneMessage = new StringBuffer();
    protected static final int MIN_DATA_LEN = 34;
    protected static final String PROTOCOL_TYPE = "EB95";
    protected static final String PROTOCOL07_TYPE = "07EB95";

    protected BaseManager() {
    }

    public abstract void processRcvMessage(String readMessage);

    public Handler handler;

    /**
     * 预处理源码
     */
    protected void processScodeForDecode() {
        String doneMessageStr = doneMessage.toString();
        String totalMessageStr = totalMessage.toString();
        int doneMessageLen = doneMessageStr.length();
        int totalMessageLen = totalMessageStr.length();
        if (doneMessageLen >= totalMessageLen) return;
        String newReadMessageStr = totalMessageStr.substring(doneMessageLen, totalMessageLen);
        String[] newReadMessageArr = newReadMessageStr.split(PROTOCOL_TYPE);
        for (String str : newReadMessageArr) {
            String realDataStr = PROTOCOL_TYPE + str;
            int dataRealLen = realDataStr.length();
            if (dataRealLen > MIN_DATA_LEN) {
                int dataCorrectLen = Integer.parseInt(realDataStr.substring(4, 6), 16) * 2 + 32;
                if (dataRealLen == dataCorrectLen) {
                    appendMessage(realDataStr, doneMessage);
                    try {
                        switchMessage(realDataStr);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

        }

    }

    /**
     * 处理消息
     */
    protected abstract void switchMessage(String realDataStr) throws Exception;

    /**
     * 追加字符串
     */
    protected void appendMessage(String appendMessage, StringBuffer orginMessage) {
        orginMessage.append(appendMessage);
    }

    protected int getDataType(String ms) {
        return Integer.parseInt(ms.substring(22, 24), 16);
    }

    /**
     * 通知Fragment
     */
    protected void sendTestMessage2Fragment(TestMessage testMessage, int what) {
        Message msg = new Message();
        Bundle data = new Bundle();
        data.putSerializable("data", testMessage);
        msg.what = what;
        msg.setData(data);
        handler.sendMessage(msg);
    }

    /**
     * 是否包含某个监测量
     */
    protected boolean hasMonitorItem(List<TestMessage> testMessages, String itemName) {

        for (TestMessage t : testMessages
        ) {
            if (itemName.equals(t.getName())) {
                return true;
            }
        }

        return false;
    }
}
